package dbs

import (
	"database/sql"
	v1config "gitee.com/scottq/go-framework/src/v1/config"
	"github.com/go-sql-driver/mysql"
	"net"
	"time"
)

func NewMysqlConn(c *v1config.DBConfig, fs ...func(config *mysql.Config)) (*sql.DB, error) {
	dbConfig := mysql.NewConfig()
	dbConfig.User = c.DbUser
	dbConfig.Passwd = c.DbPassword
	dbConfig.Net = "tcp"
	dbConfig.Addr = net.JoinHostPort(c.DbHost, c.DbPort)
	dbConfig.DBName = c.DbName
	dbConfig.MultiStatements = true
	dbConfig.RejectReadOnly = false
	dbConfig.ParseTime = true
	extParam := make(map[string]string)
	if c.MaxConcatLen != "" {
		extParam["group_concat_max_len"] = c.MaxConcatLen
	}
	dbConfig.Params = extParam

	if len(fs) > 0 {
		for _, f := range fs {
			f(dbConfig)
		}
	}

	newDb, err := sql.Open("mysql", dbConfig.FormatDSN())
	if err != nil {
		return nil, err
	}

	//默认
	newDb.SetMaxIdleConns(MaxIdleConns)
	newDb.SetMaxOpenConns(MaxOpenConns)
	newDb.SetConnMaxLifetime(MaxLifeTime)
	newDb.SetConnMaxIdleTime(MaxIdleTime)

	if c.MaxIdleConns > 0 {
		//预留并发链接数
		newDb.SetMaxIdleConns(c.MaxIdleConns)
	}
	if c.MaxOpenConns > 0 {
		//最大支持链接
		newDb.SetMaxOpenConns(c.MaxOpenConns)
	}
	if c.MaxLifetime > 0 {
		//每个链接最大生存时间
		newDb.SetConnMaxLifetime(time.Duration(c.MaxLifetime))
	}
	if c.MaxIdleTime > 0 {
		//每个链接最大空闲时间
		newDb.SetConnMaxIdleTime(time.Duration(c.MaxIdleTime))
	}
	return newDb, nil
}
